<script lang="ts" setup>
import type { VbenFormProps } from '#/adapter/form'
import type { VxeGridProps } from '#/adapter/vxe-table'
import TableAction from '#/components/TableAction/index.vue'
import { useTableCURD } from '#/hooks/useTableList'
import { Page } from '@vben/common-ui'
import {
    Button,
    Avatar,
    message,
    Modal,
    Row,
    Col,
    UploadDragger,
    FormItem,
    Input,
    Popconfirm
} from 'ant-design-vue'
import AddEditModal from './components/AddEditModal.vue'
import { columns, formSchema } from './data/table'
import type { TableListItem } from './use/api'
import { PageApi } from './use/api'
import { ref, onUnmounted, onMounted } from 'vue'
// 添加 props 定义
const props = defineProps<{
    id?: number | string
}>()
const id = ref(props.id || '1')

// 当接收的id变化时可以执行相应操作
onMounted(() => {
    if (props.id) {
        id.value = props.id
        console.log('收到参数:', props.id)
    }
})
const isComplete = ref<boolean>(true)
var timer = ref<any>(null)
var formValues = { batchNumber: '' }
var formObj = {
    regNum: '', //每次注册数量
    intervalSeconds: '' //时间间隔
}
var workId: any = ref('') //工作id
var workInfo = ref<any>({})

const formOptions: VbenFormProps = {
    schema: formSchema
}

const gridOptions: VxeGridProps<any> = {
    columns,
    proxyConfig: {
        ajax: {
            query: async ({ page }: any, formValues2: any) => {
                if (formValues2.createTime) {
                    formValues2.startTime = formValues2.createTime[0]
                    formValues2.endTime = formValues2.createTime[1]
                    delete formValues2.createTime
                }
                const res = await PageApi.getPageList({
                    ...formValues,
                    ...formValues2,
                    networkGroupId: props.id,
                    limit: page.pageSize,
                    page: page.currentPage
                })
                return {
                    items: res.records,
                    total: res.total
                }
            }
        }
    },
    // height: 500,
    // scrollY: {
    //     enabled: true,
    //     gt: 0
    // },
    showOverflow: true,
    cellConfig: {
        height: 120
    }
}

/**
 * 表格配置
 */
const {
    Grid,
    GridApi,
    reload,
    FormModal,
    add: handleCreate,
    edit: handleEdit,
    handleSuccess
} = useTableCURD<TableListItem>({
    formOptions,
    gridOptions,
    modalOptions: {
        connectedComponent: AddEditModal
    },
    delApi: PageApi.delete
})

function handleCreateFix() {
    handleCreate({
        treeData: GridApi.grid.getTableData().tableData
    })
}

/**
 * table 操作
 * @param record
 */
function getActions(record: TableListItem) {
    const arr: any[] = [
        {
            label: '修改',
            onClick: () => {
                handleEdit(record)
            }
        },
        {
            label: '删除',
            onClick: () => {
                handleEdit(record)
            }
        },
        {
            label: '重置环境',
            onClick: () => {
                handleEdit(record)
            }
        },
        {
            label: '登录',
            onClick: () => {
                handleEdit(record)
            }
        }
    ]

    return arr
}
// 导出
function handleExport() {
    PageApi.export()
}
// 在组件卸载时清除定时器
onUnmounted(() => {
    if (timer.value) {
        clearInterval(timer.value)
        timer.value = null
    }
})
// 开始工作
const handleStart = async () => {
    // 验证注册数量是否为有效的正整数
    const regNum = Number(formObj.regNum)
    if (!formObj.regNum || isNaN(regNum) || regNum <= 0 || !Number.isInteger(regNum)) {
        message.error('请输入有效的注册数量')
        return
    }

    // 验证时间间隔是否为有效的正数
    const intervalSeconds = Number(formObj.intervalSeconds)
    if (
        !formObj.intervalSeconds ||
        isNaN(intervalSeconds) ||
        intervalSeconds <= 0 ||
        !Number.isInteger(intervalSeconds)
    ) {
        message.error('请输入有效的时间间隔')
        return
    }
    // 拿工作id
    const res = await PageApi.start({
        ...formValues,
        ...formObj
    })
    workId.value = res
    if (workId.value) {
        message.success('开始工作...')
        const res = await PageApi.readWorkProgress(workId.value)
        isComplete.value = res.isComplete
        workInfo.value = res
        // 轮询
        timer.value = setInterval(async () => {
            if (isComplete.value) {
                return false
            }
            const res = await PageApi.readWorkProgress(workId.value)
            isComplete.value = res.isComplete
            workInfo.value = res
            if (isComplete.value) {
                message.success('工作完成')
                clearInterval(timer.value)
            }
        }, 1000)
    }
}
// 结束工作
const handleEnd = async () => {
    if (isComplete.value) {
        message.error('工作已完成，不能重复结束')
        return
    }
    const res = await PageApi.endWork(workId.value)
    if (res) {
        clearInterval(timer.value)
        isComplete.value = true
        message.success('结束成功')
    }
}
// 清空数据
const handleClear = async () => {
    if (!isComplete.value) {
        message.error('工作未完成，不能清空数据')
        return
    }
    const res = await PageApi.clear(formValues.batchNumber)
    if (res) {
        formValues.batchNumber = ''
        reload()
        message.success('清空成功')
    }
}
// 登录
const handleLogin = async () => {
    const res = await PageApi.login()
    if (res) {
        message.success('登录成功')
    }
}
// 刷新列表
const handleReload = () => {
    reload()
}
// 导入账号
const open = ref(false)
const fileList = ref([])
const objFile: any = ref({})
const logObj: any = ref({})
// 上传文件
const handleUpload = async (file: any, fileList: any) => {
    logObj.value = {}
    fileList = fileList
    objFile.value = file
    return false
}
async function handleOk() {
    if (objFile.value?.name) {
        const res = await PageApi.upload({ file: objFile.value })
        logObj.value = res
        if (res.batchNumber) {
            message.success('上传成功')
            formValues.batchNumber = res.batchNumber
            reload()
        } else {
            message.error('上传失败')
        }
    }
}
const titleText = formValues.batchNumber ? '确定清空当前批次的数据吗？' : '确定清空所有的数据吗？'
</script>

<template>
    <Page>
        <Grid>
            <template #toolbar-tools>
                <view class="flex gap-2">
                    <Button @click="open = true">导入账号</Button>
                    <Button type="primary" @click="handleExport"> 导出账号 </Button>
                    <Button type="primary" @click="handleCreateFix"> 自动分配网络分组 </Button>
                    <Button type="primary" @click="handleLogin"> 批量登录 </Button>
                    <Button type="primary" @click="handleCreateFix"> 批量修改备注 </Button>
                    <Popconfirm :title="titleText" @confirm="handleClear">
                        <Button danger> 清空数据 </Button>
                    </Popconfirm>
                    <Button danger type="primary" @click="handleCreateFix"> 批量重置环境 </Button>
                </view>
            </template>
            <template #emailVerified="{ row }">
                {{
                    row.emailVerified === null ? '未验证' : row.emailVerified ? '已验证' : '未激活'
                }}
            </template>
            <template #avatar="{ row }">
                <div class="flex items-center">
                    <Avatar :size="64" :src="row.avatarUrl" class="mr-2" />
                    <div class="flex min-w-0 flex-1 flex-col text-left">
                        <div class="text-base/1.5 line-clamp-1 font-semibold">
                            <Tooltip title="123">
                                <p
                                    class="text-block-500 overflow-hidden text-ellipsis whitespace-nowrap text-base"
                                >
                                    账号id：{{ row.id }}
                                </p>
                            </Tooltip>
                        </div>
                        <div>
                            <span class="text-xs text-[#B9B9B9]">账号名：{{ row.username }}</span>
                        </div>
                        <div>
                            <span class="text-xs text-[#B9B9B9]">昵称：{{ row.name }}</span>
                        </div>
                    </div>
                </div>
            </template>
            <template #action="{ row }">
                <TableAction :actions="getActions(row)" />
            </template>
        </Grid>
        <Row class="form-item-spacing bg-card pl-3" v-if="false">
            <Col span="12" class="pb-10">
                <Row>
                    <Col span="8">
                        <FormItem label="注册成功" name="customerName">
                            {{ workInfo.successNum }}个
                        </FormItem>
                    </Col>
                    <Col span="8">
                        <FormItem label="注册失败" name="contactPhone">
                            {{ workInfo.failureNum }}个
                        </FormItem>
                    </Col>
                </Row>
                <Row>
                    <Col span="8">
                        <FormItem label="每次注册" name="contactPhone">
                            <Input placeholder="个" v-model:value="formObj.regNum" />
                        </FormItem>
                    </Col>
                    <Col span="8">
                        <FormItem label="时间间隔" name="customerName">
                            <Input placeholder="秒" v-model:value="formObj.intervalSeconds" />
                        </FormItem>
                    </Col>
                </Row>
                <Button :loading="!isComplete" type="primary" class="mr-2" @click="handleStart">
                    开始工作
                </Button>
                <Button danger @click="handleEnd"> 结束工作 </Button>
            </Col>
            <Col
                span="12"
                class="pb-10"
                style="
                    min-height: 400px;
                    max-height: 400px;
                    overflow-y: auto;
                    background-color: black;
                "
            >
                <Button style="color: chartreuse" type="text" :loading="true" v-if="!isComplete"
                    >读取中...</Button
                >
                <p
                    class="pt-3"
                    v-for="item in workInfo.logList ? [...workInfo.logList].sort().reverse() : []"
                    :key="item"
                >
                    <span style="color: chartreuse; padding: 10px">{{ item }}</span>
                </p>
            </Col>
        </Row>
        <Modal v-model:open="open" title="导入" @ok="handleOk">
            <a
                style="color: #278df2; display: inline-block"
                class="pb-3"
                href="/api/export/template"
                download="注册导入模版.xlsx"
                >下载模版</a
            >
            <UploadDragger
                v-model:fileList="fileList"
                name="file"
                :multiple="true"
                :maxCount="1"
                :directory="false"
                :accept="'.xls,.xlsx'"
                :beforeUpload="handleUpload"
            >
                <p class="ant-upload-drag-icon">
                    <inbox-outlined></inbox-outlined>
                </p>
                <p class="ant-upload-text">上传导入文件</p>
                <p class="ant-upload-hint">文件格式xls，xlsx</p>
            </UploadDragger>
            <div>
                <div class="text-red-500" v-if="logObj.failureNum">导入失败数量"{{ logObj.failureNum }}"原因：</div>
                <ul>
                    <li v-for="item in logObj.failureLogList" :key="item.username">{{ item }}</li>
                </ul>
                <div style="color: greenyellow" v-if="logObj.successNum">导入成功数量{{ logObj.successNum }}</div>
                <ul>
                    <li v-for="item in logObj.successLogList" :key="item.username">{{ item }}</li>
                </ul>
            </div>
        </Modal>
        <FormModal @success="handleSuccess" @reload="handleReload" />
        <ImportModal />
    </Page>
</template>
